package utils

import (
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"math/rand"
	"strconv"
	"time"
)

var stSigningKey = []byte("fqyb")

type JwtCastClaims struct {
	ID     primitive.ObjectID
	UserId string
	Email  string
	jwt.RegisteredClaims
}

// 用来生成Token的函数
func GenerateToken(id string, email string) (string, error) {
	userId, _ := primitive.ObjectIDFromHex(id)
	var tokenTime = time.Duration(viper.GetInt("token.time"))
	iJwtCastClaims := JwtCastClaims{
		ID:     userId,
		Email:  email,
		UserId: id,
		RegisteredClaims: jwt.RegisteredClaims{
			//设置过期时间
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(tokenTime * time.Minute)),
			//token的签发时间
			IssuedAt: jwt.NewNumericDate(time.Now()),
			Subject:  "Token",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, iJwtCastClaims)

	return token.SignedString(stSigningKey)
}

// 用来解析Token
func ParseToken(tokenStr string) (JwtCastClaims, error) {
	iJwtCasClaims := JwtCastClaims{}
	token, err := jwt.ParseWithClaims(tokenStr, &iJwtCasClaims, func(token *jwt.Token) (interface{}, error) {
		return stSigningKey, nil
	})
	if err == nil && !token.Valid {
		err = errors.New("invalid Token")
	}
	return iJwtCasClaims, err
}

func IsTokenValid(tokenStr string) bool {
	_, err := ParseToken(tokenStr)
	if err != nil {
		return false
	}
	return true
}

func GetCode() string {
	rand.Seed(time.Now().UnixNano())
	res := ""
	for i := 0; i < 6; i++ {
		res += strconv.Itoa(rand.Intn(10))
	}
	return res
}

// GetUUID
// 生成唯一码
func GetUUID() string {
	u := uuid.New()
	return fmt.Sprintf("%x", u)

}
